package com.xiaoma.common.observer.lifecycle

import androidx.lifecycle.LifecycleCoroutineScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

/**
 * author: liangjingbo
 * date: 2022/11/14
 * describe:
 */
open class LifecycleObservable<T>(
    replay: Int = 0,
    extraBufferCapacity: Int = 0,
    onBufferOverflow: BufferOverflow = BufferOverflow.SUSPEND
) {

    private val mShareFlow = MutableSharedFlow<T>(
        replay = replay,
        extraBufferCapacity = extraBufferCapacity,
        onBufferOverflow = onBufferOverflow
    )

    /**
     * 订阅
     */
    fun observer(
        lifecycleCoroutineScope: LifecycleCoroutineScope,
        state: State = State.RESUME,
        observer: LifecycleObserver<T>
    ) {
        when (state) {
            State.CREATE -> {
                lifecycleCoroutineScope.launchWhenCreated {
                    collectValue(observer)
                }
            }
            State.START -> {
                lifecycleCoroutineScope.launchWhenStarted {
                    collectValue(observer)
                }
            }
            State.RESUME -> {
                lifecycleCoroutineScope.launchWhenResumed {
                    collectValue(observer)
                }
            }
        }
    }

    /**
     * 发送数据
     * @param coroutineScope CoroutineScope
     * @param value T
     */
    fun dispatchValue(
        coroutineScope: CoroutineScope,
        value: T
    ) {
        coroutineScope.launch {
            mShareFlow.emit(value)
        }
    }

    private suspend fun collectValue(lifecycleObserver: LifecycleObserver<T>) {
        mShareFlow.collect {
            lifecycleObserver.onChange(it)
        }
    }

    enum class State {
        CREATE, START, RESUME
    }

}